<script setup lang="tsx">
import { computed, ref, onMounted } from 'vue';
import { NButton, NFlex, NInput, NSpin, useMessage } from 'naive-ui';
import {
  ProEditDataTable,
  ProEditDataTableColumns,
  ProEditDataTableColumn,
  ProForm,
  ProConfigProvider,
  createProForm
} from 'pro-naive-ui';
import ConfigProvider from '../../ConfigProvider.vue';
import { fetchPdaAuthList, fetchDeletePdaAuth, fetchAddPdaAuth } from '@/service/api/pda';

interface PdaAuthItem {
  id: string;
  code: string;
  remark: string;
  [key: string]: any;
}

// 后端列配置类型
interface ColumnMeta {
  field: string;
  title: string;
  width?: number;
}

// 状态管理
const message = useMessage();
const editableKeys = ref<string[]>([]);
const loading = ref(false);
const keyword = ref(''); // 搜索关键词
const allData = ref<PdaAuthItem[]>([]);
const columnsMeta = ref<ColumnMeta[]>([
  { field: 'code', title: '授权码', width: 300 },
  { field: 'remark', title: '备注', width: 400 }
]);

// 表单初始化
const form = createProForm({
  initialValues: { list: [] as PdaAuthItem[] },
  onSubmit: async (values) => {
    try {
      loading.value = true;
      const newItem = values.list.find(item => !item.id);
      if (!newItem) {
        message.warning('请先添加数据');
        return;
      }

      const submitParams: { code: string; remark: string } = {
        code: newItem.code.trim() || '',
        remark: newItem.remark.trim() || ''
      };
      await fetchAddPdaAuth(submitParams);

      message.success('保存成功');
      loadData();
      editableKeys.value = [];
      form.values.value = { list: [] };
    } catch (e) {
      message.error('保存失败');
    } finally {
      loading.value = false;
    }
  }
});

// 加载后端数据和列配置
async function loadData() {
  loading.value = true;
  try {
    const { data: res } = await fetchPdaAuthList({ page: 1, pageSize: 100 });
    // 后端列配置优先
    columnsMeta.value = res.columnsMeta?.length ? res.columnsMeta : columnsMeta.value;
    // 存储全量原始数据
    allData.value = (res.records || []) as PdaAuthItem[];
    // 加载完成后执行一次筛选
    applyFilter();
  } catch (e) {
    message.error('数据加载失败');
  } finally {
    loading.value = false;
  }
}

// 搜索筛选核心逻辑
function applyFilter() {
  const keywordTrim = keyword.value.trim().toLowerCase();
  // 基于全量数据筛选
  const filteredData = allData.value.filter(item => {
    // 遍历当前行所有字段
    return Object.entries(item).some(([key, value]) => {
      // 跳过id字段
      if (key === 'id') return false;
      // 处理空值
      const valueStr = value?.toString().toLowerCase() || '';
      // 关键词匹配
      return valueStr.includes(keywordTrim);
    });
  });

  // 将筛选后的数据赋值给表单（表格渲染用）
  form.values.value.list = filteredData;

  // 搜索反馈
  if (keywordTrim) {
    message.info(filteredData.length === 0
      ? `未找到包含"${keywordTrim}"的记录`
      : `找到 ${filteredData.length} 条匹配记录`
    );
  }
}

// 搜索触发（统一入口：支持回车和按钮点击）
function handleSearch() {
  // 若未加载过数据，先加载全量数据再筛选
  if (allData.value.length === 0) {
    loadData();
  } else {
    applyFilter();
  }
}

// 清空搜索（修复：确保关键词清空后重新筛选）
function clearSearch() {
  keyword.value = '';
  applyFilter();
}

// 动态生成表格列配置
const columns = computed<ProEditDataTableColumns<PdaAuthItem>>(() => {
  const dynamicColumns: ProEditDataTableColumn<PdaAuthItem>[] = columnsMeta.value.map(meta => ({
    title: meta.title,
    path: meta.field,
    width: meta.width || 200,
    field: 'input' as const,
    disabled: (row: PdaAuthItem) => !editableKeys.value.includes(row.id),
    fieldProps: { placeholder: `请输入${meta.title}` }
  }));

  const actionColumn: ProEditDataTableColumn<PdaAuthItem> = {
    title: '操作',
    width: 180,
    fixed: 'right',
    render: (row: PdaAuthItem, rowIndex: number, { remove }: { remove: (index: number) => void }) => (
      <NFlex size={8}>
        {editableKeys.value.includes(row.id) ? (
          <NButton text type="primary" onClick={() => editableKeys.value = editableKeys.value.filter(k => k !== row.id)}>
            保存
          </NButton>
        ) : (
          <>
            <NButton text type="primary" onClick={() => editableKeys.value.push(row.id)}>
              编辑
            </NButton>
            <NButton
              text
              type="error"
              onClick={async () => {
                try {
                  await fetchDeletePdaAuth(row.id);
                  remove(rowIndex);
                  allData.value = allData.value.filter(item => item.id !== row.id);
                  message.success('删除成功');
                } catch (e) {
                  message.error('删除失败');
                }
              }}
            >
              删除
            </NButton>
          </>
        )}
      </NFlex>
    )
  };

  return [...dynamicColumns, actionColumn];
});

// 初始化加载
onMounted(loadData);
</script>

<template>
  <ConfigProvider>
    <ProForm :form="form" label-placement="left">
      <ProConfigProvider :prop-overrides="{ ProFormItem: { showFeedback: false } }">
        <!-- 搜索区域（修复：绑定正确的事件和逻辑） -->
        <div class="search-bar">
          <NInput v-model:value="keyword" placeholder="请输入授权码/备注/其他字段搜索" @keyup.enter="handleSearch"
            class="search-input" />
          <NButton type="primary" @click="handleSearch">查询</NButton> <!-- 按钮触发搜索 -->
          <NButton v-if="keyword" @click="clearSearch">清空</NButton> <!-- 清空搜索 -->
        </div>

        <NSpin :show="loading">
          <ProEditDataTable v-model:editable-keys="editableKeys" path="list" :columns="columns" :record-creator-props="{
            record: (): PdaAuthItem => ({ id: '', code: '', remark: '' })
          }" row-key="id" :pagination="false" class="data-table">
            <template #toolbar>
              <NFlex>
                <NButton attr-type="reset">重置</NButton>
                <NButton type="primary" attr-type="submit">保存</NButton>
              </NFlex>
            </template>
          </ProEditDataTable>
        </NSpin>
      </ProConfigProvider>
    </ProForm>
  </ConfigProvider>
</template>

<style scoped>
.search-bar {
  margin: 16px 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 300px;
}

.data-table {
  border: 1px solid var(--n-border-color);
  border-radius: 6px;
}

</style>
